#!/bin/sh
%BUTCH_CONFIG
get_file_name() {
printf "%s" "$1" | awk '{n=split($0,a,"/");print a[n];}'
}
get_file_size() {
wc -c "$1" | cut -d " " -f 1
}
check_sha512() {
[ $(sha512sum "$2"|cut -d " " -f 1) = "$1" ] && return 0
return 1
}
fail() {
	printf "ERROR: %s\n" "$1" >&2
}

if [ -z "$tarball" ] ; then
for i in %BUTCH_MIRROR_URLS ; do
	tarball=$(get_file_name "$i")
	break
done
fi
if [ -e "$C"/"$tarball" ] ; then
	[ "$filesize" = $(get_file_size "$C"/"$tarball") ] && {
		echo "tarball existing, passed size check. exiting."
		exit 0
	}
	fail "tarball exists but size differs from recipe"
	exit 99
fi
retries=5
butch_cache_dir="$C"
tmp=/tmp/butchdl.$$
rc=0
append() {
eval "$1=\"\${$1} \$2\""
eval "$1=\${$1# }"
}

download() {
	local url="$1"
	local out="$2"
	if [ "$USE_CURL" = 1 ] ; then
		curl -c /dev/null -C - --retry $retries -k -L "$url" -o "$out"
	else
		if ! wget --help 2>&1 | grep BusyBox > /dev/null ; then
			append wgetflags "--tries=$retries"
			append wgetflags --no-check-certificate
		fi
		wget $wgetflags -O "$out" -c "$url"
	fi
}

cleanup() {
	[ -e "$tmp" ] && { cat $tmp ; rm $tmp ; }
}

FALLBACK_MIRROR=http://tar.sabotage.tech
FALLBACK=$FALLBACK_MIRROR/%BUTCH_PACKAGE_NAME/$tarball
echo "in case the download process was killed, see $tmp for wget/curl output"
for url in %BUTCH_MIRROR_URLS $FALLBACK ; do
if ! download "$url" "$butch_cache_dir/$tarball".wip >$tmp 2>&1 ; then
	rc=1
	grep 404 < $tmp > /dev/null && { rc=44 ; fail "HTTP 404 FILE NOT FOUND" ; }
	[ "$rc" = 1 ] && fail "UNKNOWN DL ERROR, SEE LOG"
	cleanup
else
	mv "$butch_cache_dir"/"$tarball".wip \
	   "$butch_cache_dir"/"$tarball"
	rc=0
	if [ -n "$filesize" ] && [ "$filesize" != $(get_file_size "$butch_cache_dir"/"$tarball") ] ; then
		rc=22
		fail "FILESIZE MISMATCH"
	fi
	if [ -n "$sha512" ] && ! check_sha512 "$sha512" "$butch_cache_dir"/"$tarball" ; then
		rc=11
		fail "SHA512 CHECKSUM MISMATCH"
	fi
	break
fi
done
cleanup
exit $rc
